package com.fausto.learnimprint.handler

import com.fausto.learnimprint.common.enum.ResultCodeEnum
import com.fausto.learnimprint.core.model.dto.CommonResult
import org.apache.catalina.connector.ClientAbortException
import org.springframework.boot.context.properties.bind.BindException
import org.springframework.security.web.firewall.RequestRejectedException
import org.springframework.web.HttpRequestMethodNotSupportedException
import org.springframework.web.bind.MissingServletRequestParameterException
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException
import org.springframework.web.servlet.NoHandlerFoundException

/*全局异常处理 */
@RestControllerAdvice
class GlobalExceptionHandler {
    /**
     * 找不到资源
     * 未找到处理器 异常
     *
     */
    @ExceptionHandler(NoHandlerFoundException::class)
    fun noHandlerFoundExceptionHandler(e: Exception): CommonResult<Any> {
        e.printStackTrace()
        return CommonResult.build(e.message, ResultCodeEnum.NOT_FOUND)
    }

    /**
     * 权限不足
     *
     */
    @ExceptionHandler(AccessDeniedException::class)
    fun accessDeniedExceptionHandler(e: Exception): CommonResult<Any> {
        e.printStackTrace()
        return CommonResult.build(e.message, ResultCodeEnum.ACCESS_ERROR)
    }

    /**
     * 请求方式错误
     *
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException::class)
    fun httpRequestMethodNotSupportedExceptionHandler(e: Exception): CommonResult<Any> {
        e.printStackTrace()
        return CommonResult.build(e.message, ResultCodeEnum.FAIL.apply { message = "HTTP请求方法不支持" })
    }

    /**
     * controller参数异常/缺少
     *
     */
    @ExceptionHandler(
        MissingServletRequestParameterException::class,
        MethodArgumentTypeMismatchException::class,
        RequestRejectedException::class,
        BindException::class
    )
    fun missingServletRequestParameterException(e: Exception): CommonResult<Any> {
        e.printStackTrace()
        return CommonResult.build(e.message, ResultCodeEnum.FAIL.apply { message = "参数错误" })
    }


    /**
     * 客户端错误
     *
     */
    @ExceptionHandler(ClientAbortException::class)
    fun clientAbortExceptionException(e: Exception): CommonResult<Any> {
        e.printStackTrace()
        return CommonResult.build(e.message, ResultCodeEnum.FAIL.apply { message = "客户端错误" })
    }

    fun emptyContent(e: Exception): CommonResult<Any> {
        e.printStackTrace()
        return CommonResult.fail("信息不足(缺少token)", data = e.message)
    }

    /**
     * 其他异常
     *
     */
    @ExceptionHandler(Exception::class)
    fun exceptionHandler(e: Exception): CommonResult<Any> {
        e.printStackTrace()
        return CommonResult.build(e.message, ResultCodeEnum.SERVICE_ERROR.apply { message = "服务端错误,请联系管理员" })
    }

}